package cn.qyd.threadsignal;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @author 邱运铎
 * @date 2024-03-25 12:04
 */
public class CountDownLatchDemo02 {
    static class PreTaskThread implements Runnable {
        private String task;
        private CountDownLatch countDownLatch;

        public PreTaskThread(String task, CountDownLatch countDownLatch) {
            this.task = task;
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            try {
                Random random = new Random();
                int loadTime = random.nextInt(5000);
                Thread.sleep(loadTime);
                countDownLatch.countDown();
                System.out.println(task + "---任务加载完成。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(() -> {
            try {
                System.out.println("等待数据加载中。。");
                System.out.println("等待游戏其他模块加载完成");
                System.out.println(String.format("游戏还剩%d前置任务等待加载", countDownLatch.getCount()));
                countDownLatch.await();
                System.out.println("游戏开始了。");

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(new PreTaskThread("地图模型加载",countDownLatch)).start();
        new Thread(new PreTaskThread("人物模型加载",countDownLatch)).start();
        new Thread(new PreTaskThread("背景音乐加载",countDownLatch)).start();
    }
}
